﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;
using System.Configuration;

namespace WebApp.Common
{

    public class AES
    {
        //默认密钥向量   
        private static byte[] _iv = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };

        public static string Encrypt(string plainText)
        {
            try
            {
                //key必须16位
                string encryptKey = ConfigurationManager.AppSettings["aes.encrypt.key"];
                if (string.IsNullOrEmpty(encryptKey))
                {
                    encryptKey = "we#win$WY$201706";
                }

                return AESEncrypt(plainText, encryptKey);
            }
            catch (Exception ex)
            {
                //Log.Error(ex);
                return plainText;
            }
        }

        public static string Decrypt(string cipherText)
        {
            try
            {
                //key必须16位
                string encryptKey = ConfigurationManager.AppSettings["aes.encrypt.key"];
                if (string.IsNullOrEmpty(encryptKey))
                {
                    encryptKey = "we#win$WY$201706";
                }

                return AESDecrypt(cipherText, encryptKey);
            }
            catch (Exception ex)
            {
                //Log.Error(ex);
                return cipherText;
            }
        }

        /// <summary>          
        /// AES加密         
        /// </summary>          
        /// <param name="inputdata">输入的数据</param>         
        /// <param name="iv">向量128位</param>         
        /// <param name="strKey">加密密钥</param>         
        /// <returns></returns>          
        public static string AESEncrypt(string plainText, string strKey)
        {
            if (string.IsNullOrEmpty(plainText)) return string.Empty;

            //分组加密算法              
            SymmetricAlgorithm des = Rijndael.Create();
            byte[] inputByteArray = Encoding.UTF8.GetBytes(plainText);//得到需要加密的字节数组

            //设置密钥及密钥向量
            if (strKey.Length > 32)
            {
                des.Key = Encoding.UTF8.GetBytes(strKey.Substring(0, 32));
            }
            else
            {
                des.Key = Encoding.UTF8.GetBytes(strKey);
            }
            des.IV = _iv;
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    byte[] cipherBytes = ms.ToArray();//得到加密后的字节数组                     
                    cs.Close();
                    ms.Close();
                    return Convert.ToBase64String(cipherBytes);
                }
            }
        }

        /// <summary>         
        /// AES解密         
        /// </summary> 
        /// <param name="inputdata">输入的数据</param>         
        /// <param name="iv">向量128</param>         
        /// <param name="strKey">key</param>         
        /// <returns></returns> 
        public static string AESDecrypt(string cipherText, string strKey)
        {
            if (string.IsNullOrEmpty(cipherText)) return string.Empty;

            SymmetricAlgorithm des = Rijndael.Create();
            if (strKey.Length > 32)
            {
                des.Key = Encoding.UTF8.GetBytes(strKey.Substring(0, 32));
            }
            else
            {
                des.Key = Encoding.UTF8.GetBytes(strKey);
            }
            des.IV = _iv;

            byte[] inputdata = Convert.FromBase64String(cipherText);
            byte[] decryptBytes = new byte[inputdata.Length];
            using (MemoryStream ms = new MemoryStream(inputdata))
            {
                using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read))
                {
                    cs.Read(decryptBytes, 0, decryptBytes.Length); cs.Close(); ms.Close();
                }
            }

            //return decryptBytes;
            return Encoding.UTF8.GetString(decryptBytes).TrimEnd('\0');
        }
    }
}
